﻿/*----------------------------------------------------------------
 
    // 版权所有。 
    // 作者：马毅
    //
 
    // 文件功能描述： 产品报价采用CA 对称加密
    //
    // 创建标识：2009-09-10
    //
    //
    // 修改描述：企业报完价将不能进去查看先前报价。采用数字信封和门限算法
    // 其他说明：此报价加密方式对企业来说不方便，但是安全，没有门限的那几KEY将无法解密         
 
 
//----------------------------------------------------------------*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.MBSM.Model;
using HZ.MBSM.BLL;
using HZ.MBSM.DBUtility;
using System.Text;
public partial class Bidder_BidPrice1ca : System.Web.UI.Page
{
    Int32 prjid;
    bool bPrint = false;
    String BP1strConditions;

    string bidprice1pwd, bidprice1rond;
    Int64 BidPrice1Accountid_TBR;
    private const int GridColumnIndexOfSPPrice = 10;
    private const int GridColumnIndexOfPriceSwitching = 12;

    //随机数
    public string strRan;
    //加密后的随机数
    public string strEncRan;
    //签名值
    public string strSignData;
    //用户证书
    public string strCert;
    //加密后证书
    public string strEncCert;
    //服务器证书
    public string strSerCert;
    //容器
    public string strContainer;
    //ca的对象
   
    BCACOMLib.SecurityEngineClass bca = new BCACOMLib.SecurityEngineClass();
    protected void Page_Load(object sender, EventArgs e)
    {

        System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
        _AccountType.Add(HZ.MBSM.DAL.AccountType.enumCompany);
        if (HZ.MBSM.BLL.Login.CheckAssert(_AccountType))
        {
            //if (Config.EnableEncrypt && !HZ.Encrypt.EncryptWrapper.SetKey)
            //{
            //    HZ.Web.MessageBox.Show("密钥尚未加载无法报价");
            //}
            strRan = Session["Random"].ToString();
            strContainer = Session["ContainerName"].ToString();
            strCert = Session["UserCert"].ToString();
            strSerCert = bca.getSelfCert();
            prjid = Int32.Parse(SysFun.IsSQL(Request.QueryString["projectid"]));//项目id
            try
            {

                //获取服务器证书
                strSerCert = bca.getSelfCert();
                //  strCert = Session["UserCert"].ToString();
                // strEncCert = Session["UserEncCert"].ToString();
                strContainer = Session["ContainerName"].ToString();
                GetstrRan(prjid.ToString());
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('" + ex.Message + "')</script>");
            }
            if (!Page.IsPostBack)
            {
                if (Session["Pass"] == null || Session["Pass"].ToString() != "OK")
                {
                    Response.Write("<script>window.alert('报价密码不正确！！');</script>");
                    Response.Write("<script>window.location=\"Nothing.aspx?Projectid=" + prjid.ToString() + "\"</script>");
                    return;
                }
               
                showGridView();
            }
            if (Request.Form["subPrint"] == "投标报价一览表")
            {
                showGridView(); PrintTable();
            }

        }
    }


    /// <summary>
    /// 查询总共有多少页
    /// </summary>
    /// <returns></returns>
    /// <summary>
    /// 将数据绑定到GridView1
    /// </summary>
    /// <param name="PageIndex">转向第几页</param>
    public void showGridView()
    {
        BP1strConditions = fctConditions();
        Db db = new Db();
        DbPage dbPage = new DbPage(db);
        dbPage.Table = "bidprice";                                               //要查询的表明
        dbPage.Key = "Bidid";                                               //表的主键    
        dbPage.Where = BP1strConditions;                                           //查询条件


        if (Config.EnableEncrypt)
        {
            dbPage.SelectField = " bidid,Goodsid,productname,outlookc,Medicinemodel,ScName,unit,factor,FactoryUserCode,Convert(Numeric(20,2),LimitPrice*factor) as LimitPricePack,Convert(Numeric(20,4),LimitPrice) as LimitPriceMin, EncryptedPrice , Smprice ,SPPrice,limitprice,PriceSwitching";//要显示的字段
        }
        else
        {
            dbPage.SelectField = " bidid,Goodsid,productname,outlookc,Medicinemodel,ScName,unit,factor,FactoryUserCode,Convert(Numeric(20,2),LimitPrice*factor) as LimitPricePack,Convert(Numeric(20,4),LimitPrice) as LimitPriceMin,Convert(Numeric(20,2),SPPrice) AS SPPrice,Convert(numeric(20,5),smprice) AS smprice,limitprice,PriceSwitching,EncryptedPrice";//要显示的字段
        }
        dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
        if (Request.Form["subPrint"] == "投标报价一览表" || Request.Form["subPrint"] == "预览并打印")
        {
            dbPage.PageSize = 1;                                                    //没有显示记录条数  
        }
        else
        {
            dbPage.PageSize = 10;                                                    //没有显示记录条数  

        }

        dbPage.OrderBy = "ProductName,Medicinemodel,Outlookc,Bidid";                  //排序字段
        System.Data.IDataReader dr = dbPage.ExecuteReader();
        GridView1.DataSource = dr;
        GridView1.DataBind();

        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键
        if (Request.Form["subPrint"] == "投标报价一览表")
        {
            PrintTable();
        }

    }

    public string fctConditions()
    {
        string strtemp;
        string PN = SysFun.ToTrim(ProductName.Text);
        string BPGoodsid = txtGoodsId.Text.Trim();
        string ComSC = txtCompanySc.Text.Trim();

        HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
        if (_Account != null)
        {
            BidPrice1Accountid_TBR = SysFun.ToLong(_Account.AccountId);
            strtemp = " AccountID_TB='" + BidPrice1Accountid_TBR.ToString() + "' and CheckStatus='1' And ProjectId=" + prjid.ToString() + " And";
            if (PN != "")
            {
                strtemp += " productname like '%" + PN + "%' And";
            }
            if (BPGoodsid != "")
            {
                strtemp += " Goodsid ='" + BPGoodsid + "' And";
            }
            if (ComSC != "")
            {
                strtemp += " ScName like '%" + ComSC + "%' And";
            }
            string _strMedicinemodel = txtMedicinemodel.Text.ToString();
            if (_strMedicinemodel != "")
            {
                strtemp += "  Medicinemodel like '%" + _strMedicinemodel + "%' And";
            }
            string _strUserCode_SC = txtUserCode_SC.Text.ToString();
            if (_strUserCode_SC != "")
            {
                strtemp += "  FactoryUserCode like '%" + _strUserCode_SC + "%' And";
            }
            string _strPriceState = lstPriceState.SelectedValue;
            switch (_strPriceState)
            {
                case "全部":
                    break;
                case "未报价":
                    strtemp += " ((spprice=0 or spprice is null) AND EncryptedPrice IS NULL) and";
                    break;
                case "已报价":
                    strtemp += " (spprice>0 OR EncryptedPrice IS NOT NULL) and";
                    break;
            }
            if (strtemp != "")
            {
                strtemp = "  " + strtemp.Substring(0, strtemp.Length - 3);
            }
        }
        else
        {
            strtemp = "";

        }
        return strtemp;


    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string bidprice = "";
            if (!string.IsNullOrEmpty(e.Row.Cells[14].Text) && e.Row.Cells[14].Text != "&nbsp;")
            {
                //HZ.Encrypt.EncryptWrapper.DecrytPrice
                //bidprice = HZ.Encrypt.EncryptWrapper.DecrytPrice(Session["bidPassword"].ToString(), e.Row.Cells[14].Text);
               // bidprice = bca.DecDataByRSA(e.Row.Cells[14].Text.Trim());
                //int a = int.Parse(e.Row.Cells[6].Text);
                //float  spprice = float.Parse(bidprice) / a;
                //e.Row.Cells[9].Text = spprice.ToString();
                //edit by ws 去掉制剂报价
            }
            if (e.Row.Cells[GridColumnIndexOfPriceSwitching].Text == "0")//判断报价开关
            {
                e.Row.Cells[8].Text = bidprice;

                Button1.Visible = false;

            }
            else
            {
                if (Request.Form["subPrint"] == "投标报价一览表")
                {
                    e.Row.Cells[8].Text = bidprice;
                }
                else
                {

                    e.Row.Cells[8].Text = "<input style='width: 60px' type='text' name='txtprice" + e.Row.Cells[0].Text + "'  value=\"" + bidprice + "\"  onblur=\"javascript:if(!/^[0-9]+(\\.[0-9]{1,3})?$/.test(this.value)){alert('流水号" + e.Row.Cells[0].Text + "请输入正确价格！');this.value='" + SysFun.OutNum(bidprice, 2) + "'}; \" /> ";


                }
                Button1.Visible = true;
            }
            // e.Row.Cells[15].Text = "  <input type=\"hidden\" name=\"H"+e.Row.Cells[0].Text+"\" id=\"H"+e.Row.Cells[0].Text+"\" /> <asp:HiddenField id=\"HP" + e.Row.Cells[0].Text + "\" runat=\"server\" Value=\"\" />";
            //HiddenField hdf01 = new HiddenField();
            //hdf01.ID = "H" + e.Row.Cells[0].Text;

            //HiddenField hdf02 = new HiddenField();
            //hdf02.ID = "HP" + e.Row.Cells[0].Text;

            //e.Row.Cells[15].Controls.Add(hdf01);
            //e.Row.Cells[15].Controls.Add(hdf02);
        }
        e.Row.Cells[0].Visible = false;//不显示BIDID
        e.Row.Cells[GridColumnIndexOfSPPrice].Visible = false;//不显示最小包装价
        e.Row.Cells[GridColumnIndexOfPriceSwitching].Visible = false;//不显示PriceSwitching
        e.Row.Cells[14].Visible = false;//不显示 
        e.Row.Cells[11].Visible = false;
        // e.Row.Cells[11].Visible = false;


    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //OverRide　为了使导出成Excel可行！

    }

    private void PrintTable()
    {


        SysFun.WriteToExcel(GridView1, this.Page, "投标报价一览表.xls");



    }
    
    #region 提交报价
    protected void Button1_Click(object sender, EventArgs e)
    {
        #region 提交报价
       
        ErrorMsg.Text = "";
        System.Text.StringBuilder smPrice = new System.Text.StringBuilder("");
        System.Text.StringBuilder spPrice = new System.Text.StringBuilder("");
        System.Text.StringBuilder bidID = new System.Text.StringBuilder("");
        System.Text.StringBuilder sqlbatchcmd = new StringBuilder();
        string strupmitprice = "";//解密后报价数值
        short isname = 0;//验证签名是否正确
        foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {

                string a = Request.Form["txtprice" + row.Cells[0].Text.Trim()];
                if (!SysFun.IsNumeric(a.Trim()))//判断输入的是否是数值
                {
                    ErrorMsg.Text += "商品流水号" + row.Cells[1].Text + "报价只能为数字<br>";
                    Response.Write("<script>window.alert('报价只能为数字！')</script>");
                }
                else
                {

                    a = Convert.ToDecimal(a.Trim()).ToString("F2");
                    //判断当前输入得值是否越界,
                    if (Convert.ToDecimal(a) < 0 || Convert.ToDecimal(a) > 99999999)
                    {
                        ErrorMsg.Text += "商品流水号" + row.Cells[1].Text + "报价数有误<br>";
                        Response.Write("<script>window.alert('报价数有误！')</script>");
                    }
                    else
                    {
                        if (SysFun.ToDec(row.Cells[7].Text) <= Convert.ToDecimal(a))
                        {
                            ErrorMsg.Text += "商品流水号" + row.Cells[1].Text + "报价不能大于限价<br>";
                            Response.Write("<script>window.alert('报价数有误！')</script>");
                            continue;
                        }

                        if (Config.EnableEncrypt)
                        {
                            try
                            {
                                //验证加密是否正确
                                
                                strupmitprice = bca.DecStr(Session["UserEncCert"].ToString(), ((HiddenField)row.Cells[15].Controls[1]).Value);
                                isname = bca.verifySignedData(((HiddenField)row.Cells[15].Controls[3]).Value, Session["UserCert"].ToString(), a);
                                if (isname != 0)
                                {
                                    ErrorMsg.Text += "商品流水号" + row.Cells[1].Text + "验证签名失败，需重新报价！<br>";
                                    Response.Write("<script>window.alert('验证签名失败，需重新报价！')</script>");
                                    continue;
                                }
                                if (SysFun.ToDec(a) != SysFun.ToDec(strupmitprice))
                                {
                                    ErrorMsg.Text += "商品流水号" + row.Cells[1].Text + "报价加密失败，需重新报价！<br>";
                                    Response.Write("<script>window.alert('加密失败，需重新报价！')</script>");
                                    continue;
                                }
                            }
                            catch
                            {
                                ErrorMsg.Text = "报价验证失败，请重新登录报价。";
                            }
                            sqlbatchcmd.AppendFormat("UPDATE Project_Bid SET EncryptedPrice = '{0}',EncryptedName='{1}', SPPrice = NULL,SMPrice = NULL WHERE BidId = {2};", ((HiddenField)row.Cells[15].Controls[1]).Value, ((HiddenField)row.Cells[15].Controls[3]).Value, row.Cells[0].Text);
                        }
                        else
                        {
                            //判断当前价格是否被修改过，如果没有修改，就不将此价格放到提交列表中
                            if (a != row.Cells[GridColumnIndexOfSPPrice].Text.ToString())
                            {
                                //包装报价
                                spPrice.Append(Convert.ToDecimal(a) + "$");
                                string _strLimtPrice = Convert.ToDecimal(Convert.ToDecimal(a) / (Convert.ToDecimal(row.Cells[6].Text))).ToString("N4");
                                //制剂报价
                                smPrice.Append(Convert.ToDecimal(_strLimtPrice) + "$");
                                bidID.Append(row.Cells[0].Text + "$");
                            }
                        }
                    }
                }
            }

            if (smPrice.ToString().Length > 0 || sqlbatchcmd.Length > 0)
            {
                if (Config.EnableEncrypt)
                {
                    Db crydb = new Db();
                    try
                    {

                        crydb.Command(sqlbatchcmd.ToString(), 120);
                    }
                    catch
                    {

                        ErrorMsg.Text = "报价失败！重试";
                    }
                    finally
                    {
                        crydb.Close();
                    }
                }
                else
                {

                    HZ.MBSM.BLL.CompanyBidding cmpBid = new HZ.MBSM.BLL.CompanyBidding();
                    if (cmpBid.BidPrice_QuotedPrice(smPrice.ToString(), spPrice.ToString(), bidID.ToString()))//执行存储过程
                    {
                        HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
                        HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "更新", "bidprice", "BidPrice_QuotedPrice", "../Bidder/BidPrice1.aspx");

                        ErrorMsg.Text += "本页报价成功，未报价做零处理";
                    }
                    else
                        ErrorMsg.Text += "报价失败！重试";
                }
            }
            showGridView();

        }

        #endregion
    }
    #endregion
    
   
    #region 获取随机数
    private string  GetstrRan(string prjid)
    {  HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
        string strRan = "";
        string select = "select strRan,strEnRan from dbo.ProjectCompanyAttribution where isnull(strRan,0)<>'0' and AccountId=" + _Account.AccountId + " and ProjectId=" + prjid;
        Db db = new Db();
        DataTable dt = db.DataTable(select);
        db.Close();
        if (dt != null && dt.Rows.Count > 0)
        {
            strEncRan = dt.Rows[0][1].ToString().Trim();
        }
        else
        {
            //生成指定长度的随机数
            strRan = bca.generateRandom(21);
       

            //信封加解密
            //分证书加密随机数参数：输入数据，用户证书，加解密标志位（1：加密、0：解密）
            //返回值：	加密结果
            strEncRan = bca.envelopedData(strRan, Session["UserEncCert"].ToString(), 1);
            bool bolSecertSegments = false;
            do
            {
                //分拆随机数存入BJ_JMCS
                bolSecertSegments = setSecertSegments(strRan, _Account.AccountId.ToString(), 3, 2,1);
            }
            while (!bolSecertSegments);
            int intResult = 0;
            do
            {
                try
                {
                    //将企业随机数加密后写入ProjectCompanyAttribution
                    EDCertCA edc = new EDCertCA();
                    intResult = edc.SaveRenByCompany(_Account.AccountId.ToString(), strRan, strEncRan, prjid);
                }
                catch (Exception ex)
                {
                   // WriteErrorLog(ex);
                }
            }
            while (intResult <= 0);
        }
        return strEncRan;
    }

    #endregion

    #region 分拆随机数存入数据库
    /// <summary>
    /// 分拆随机数存入数据库
    /// </summary>
    /// <param name="strRan">获取的21位随机数</param>
    /// <param name="LC_BH">轮次编号</param>
    /// <param name="EncNum">加密人数</param>
    /// <param name="EncNeedNum">需要加密人数</param>
    /// <param name="EncRecoveryNeedNum">还原时，必须参加的份数</param>
    /// <returns></returns>
    protected bool setSecertSegments(string strRan, string AccountId_qy,int EncNum, int EncNeedNum, int EncRecoveryNeedNum)
    {
 
        BCACOMLib.SecurityEngineClass sec = new BCACOMLib.SecurityEngineClass();

        // bool _SecertSegments = false;
        //对输入数据创建门限密钥
        //参数说明： 待分组数据， 分组份数，还原所需最少份数，还原时必须参加的分数
        //返回分组后的密钥用”&&&”分割；错误，返回其他
        string strEncRan = sec.SecertSegment(strRan, EncNum, EncNeedNum, EncRecoveryNeedNum);

        string[] SecertSegments = strEncRan.Split("&&&".ToCharArray());
        EDCertCA edc = new EDCertCA();
        DataTable CAdata = edc.GetEDCertCA(Int32.Parse(SysFun.IsSQL(Request.QueryString["projectid"])));
        string _strRenXF = "", _strSupXF = "",_straccountid="";//拆分后的随机数片段用门限密钥加密，拆分后的随机数片段用超级密钥加密，解密key的用户id
        for (int i = 0, j = 0; i < SecertSegments.Length && j < EncNum; i++)
        {
            if (!SecertSegments[i].Equals(""))
            {

                // P7格式数字信封加解密：输入数据（加密时为原文、解密时为密文），用户证书，加解密标志位（1：加密、0：解密）
                //返回值：	加密结果
                _strRenXF = sec.envelopedData(SecertSegments[i], CAdata.Rows[j]["jm_cert_zs"].ToString(), 1);

                //P7格式数字信封加解密：输入数据（加密时为原文、解密时为密文），用户证书，加解密标志位（1：加密、0：解密）
                //分证书加密随机数参数：输入数据，用户证书，加解密标志位（1：加密、0：解密）
                //返回值：	加密结果
                _strSupXF = sec.envelopedData(strRan, CAdata.Select("issuper =1")[0]["jm_cert_zs"].ToString(), 1);
                _straccountid = CAdata.Rows[j]["jm_accountid"].ToString();
                
                //添加
                int intResult = 0;
                do
                {
                    try
                    {
                        //将企业随机数加密后写入JM_RenByKey
                        intResult = edc.SaveRendoor(1, AccountId_qy, CAdata.Rows[j]["JM_id"].ToString(), _strRenXF, _strSupXF);
                    }
                    catch (Exception ex)
                    {
                       //WriteErrorLog(ex);
                    }
                }
                while (intResult <= 0);

                j++;
            }
        }
        return true;
    }
    #endregion
}
